package me.sealer.transformer;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.IOException;

/**
 * 功能描述： java对象和xml报文互转
 *
 * @author sealer
 * @email 1178884049@qq.com
 * @date 2019年03月17日 13时40分26秒
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class JxmlTransformer {
    private XmlMapper xmlMapper;

    public <T> T xmlStringToJava(String xmlString, TypeReference<T> typeReference) throws IOException {
        return xmlMapper.readValue(xmlString, typeReference);
    }

    public <T> T xmlBytesToJava(byte[] xmlBytes, TypeReference<T> typeReference) throws IOException {
        return xmlMapper.readValue(xmlBytes, typeReference);
    }

    public <T> T xmlStringToJava(String xmlString, Class<T> typeReference) throws IOException {
        return xmlMapper.readValue(xmlString, typeReference);
    }

    public <T> T xmlBytesToJava(byte[] xmlBytes, Class<T> typeReference) throws IOException {
        return xmlMapper.readValue(xmlBytes, typeReference);
    }

    public <T> String javaToXmlString(T t) throws JsonProcessingException {
        return xmlMapper.writeValueAsString(t);
    }

    public <T> byte[] javaToXmlBytes(T t) throws JsonProcessingException {
        return xmlMapper.writeValueAsBytes(t);
    }
}
